package cn.scw.project.separate.service.impl;

import cn.scw.common.constant.Constants;
import cn.scw.common.constant.HttpStatus;
import cn.scw.common.separate.SeparateMethod;
import cn.scw.common.separate.model.RegisterModel;
import cn.scw.common.separate.response.BaseResponse;
import cn.scw.common.utils.StringUtils;
import cn.scw.common.utils.ZipUtils;
import cn.scw.common.utils.pay.ConfigUtil;
import cn.scw.common.utils.pay.PayUtils;
import cn.scw.framework.manager.AsyncManager;
import cn.scw.framework.manager.factory.AsyncFactory;
import cn.scw.framework.web.domain.AjaxResult;
import cn.scw.project.separate.controller.AsyncTask;
import cn.scw.project.separate.domain.SaUser;
import cn.scw.project.separate.domain.SaUserImg;
import cn.scw.project.separate.mapper.SaUserMapper;
import cn.scw.project.separate.service.SaUserImgService;
import cn.scw.project.separate.service.SaUserService;
import com.alibaba.fastjson.JSONObject;
import org.jdom.JDOMException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SaUserServiceImpl implements SaUserService {

    @Resource
    private SaUserMapper saUserMapper;

    @Resource
    private SaUserImgService saUserImgService;

    @Resource
    private SeparateMethod separateMethod;

    private int i = 0;

    @Override
    //2021-11-14作废原有分账商户添加接口有saveNew替代
    public Long save(SaUser user) {
        if (user.getId() != null) {
            if (user.getIsCompete() != null && user.getIsCompete().compareTo(3) >= 0) user.setState(0);
            saUserMapper.update(user);
        } else {
            user.setCreateDate(new Date());
            user.setIsDeleted(0);
            user.setState(-1);
            user.setIsBind(0);
            saUserMapper.insert(user);
        }
        if (StringUtils.isNotBlank(user.getFileInfo())) {
            SaUserImg saUserImg = saUserImgService.selectByUserId(user.getId());
            if (saUserImg == null) saUserImg = new SaUserImg();
            else {
                saUserImg.setFileInfo(user.getFileInfo());
            }
            saUserImg.setUserId(user.getId());
            saUserImgService.save(saUserImg);

            if (user.getIsCompete().compareTo(3) >= 0) {
                submitRegister(user, saUserImg);
            }
        }
        return user.getId();
    }

    @Override
    public Long saveNew(SaUser user) {
        if (user.getId() != null) {
            user.setState(0);
            saUserMapper.update(user);
            //接口调用添加分账接收方
            profitSharingAdd(user);
        } else {
            user.setCreateDate(new Date());
            user.setIsDeleted(0);
            user.setState(0);
            user.setIsBind(0);
            saUserMapper.insert(user);
            //接口调用添加分账接收方
            profitSharingAdd(user);
        }
        return user.getId();
    }


    public void profitSharingAdd(SaUser user) {

            try {
                String mrchType = ConfigUtil.PERSONAL_OPENID;
                String openId = user.getOpenId();
                if(StringUtils.isNotEmpty(user.getMercNo())){
                    mrchType = ConfigUtil.MERCHANT_ID;
                    openId = user.getMercNo();
                }
                AjaxResult result = PayUtils.profitSharingAddReceiver(mrchType,user.getIdentityName(),openId);
                if((Integer)result.get(result.CODE_TAG)==HttpStatus.SUCCESS){
                    user.setState(1);
                    saUserMapper.update(user);
                }else{
                    user.setState(2);
                    user.setErrMsg(result.get(result.MSG_TAG).toString());
                    saUserMapper.update(user);
                }
            } catch (JDOMException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    public void profitSharingDelete(SaUser user) {

        try {
            String mrchType = ConfigUtil.PERSONAL_OPENID;
            String openId = user.getOpenId();
            if(StringUtils.isNotEmpty(user.getMercNo())){
                mrchType = ConfigUtil.MERCHANT_ID;
                openId = user.getMercNo();
            }
            AjaxResult result = PayUtils.profitSharingDeleteReceiver(mrchType,user.getIdentityName(),openId);
            if((Integer)result.get(result.CODE_TAG)==HttpStatus.SUCCESS){
                user.setErrMsg(result.get(result.MSG_TAG).toString()+"(微信分账接收方删除)");
                saUserMapper.update(user);
            }else{
                user.setErrMsg(result.get(result.MSG_TAG).toString());
                saUserMapper.update(user);
            }
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    /**
     * 注册商户
     *
     * @param user
     */
    private void submitRegister(SaUser user, SaUserImg saUserImg) {
        i++;
        System.out.println("注册进件商户事务处理" + i);
        String requestId = user.getId() + "_" + System.currentTimeMillis();
        SaUser saUser = saUserMapper.select(user.getId());
        if (saUser.getState().compareTo(0) == 0) {
            //调用随身付注册商户接口
            //图片打包上传
            String filePath = Constants.UPLOAD_FILE + "/upload/store/" + user.getId();
            File file = new File(filePath);
            if (!file.exists()) file.mkdirs();
            ZipUtils.zip(filePath, "imageCode");
            String fileCode = separateMethod.updateFile(filePath + "/imageCode.zip", StringUtils.isBlank(saUserImg.getFileCode()) ? "" : saUserImg.getFileCode());
            saUserImg.setFileCode(fileCode);
            saUserImgService.save(saUserImg);

            registerAccount(user, saUserImg, requestId);
        }
    }

    private void registerAccount(SaUser user, SaUserImg saUserImg, String requestId) {
        if (StringUtils.isNotBlank(saUserImg.getFileCode())) {
            RegisterModel registerModel = JSONObject.parseObject(JSONObject.toJSONString(user), RegisterModel.class);
            registerModel.setRequestId(requestId);
            registerModel.setFileCode(saUserImg.getFileCode());
            registerModel.setStmManIdNo(user.getStmManIdMo());
            BaseResponse response = separateMethod.registerAccount(registerModel);
            if (!response.getSuccess()) {
                //提交失败
                user.setState(99);
                user.setErrMsg(response.getRetMsg());
                saUserMapper.update(user);
            }
        }
    }

    @Override
    public void delete(Long id) {
        SaUser user = new SaUser();
        user.setId(id);
        user.setIsDeleted(1);
        saUserMapper.update(user);
    }

    @Override
    public void delete(Long[] id) {
        for (Long i : id){
            delete(i);
            SaUser saUser = select(i);
            profitSharingDelete(saUser);
        }
    }

    @Override
    public void clear(Long id) {
        saUserMapper.delete(id);
    }

    @Override
    public List<SaUser> list(Map<String, Object> params) {
        return saUserMapper.list(params);
    }

    @Override
    public SaUser select(Long id) {
        return saUserMapper.select(id);
    }

    @Override
    public List<SaUser> queryFacUser(String facId) {
        return saUserMapper.queryFacUser(facId);
    }

    @Override
    public SaUser selectOpenId(String openid) {
        return saUserMapper.selectOpenId(openid);
    }
}
